package com.foreverwin.mes.integration.soap.material.service.impl;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.integration.enums.ResponseStatus;
import com.foreverwin.mes.integration.soap.material.dto.MaterialBasicData;
import com.foreverwin.mes.integration.soap.material.dto.MaterialPlantData;
import com.foreverwin.mes.integration.soap.material.dto.MaterialReplicateRequest;
import com.foreverwin.mes.integration.soap.material.dto.WebServiceResponse;
import com.foreverwin.mes.integration.soap.material.service.MaterialReplicateService;
import com.sap.me.common.CustomValue;
import com.sap.me.common.ItemType;
import com.sap.me.common.ObjectReference;
import com.sap.me.extension.Services;
import com.sap.me.frame.domain.BusinessException;
import com.sap.me.frame.transitionutils.Exceptions;
import com.sap.me.productdefinition.*;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Component;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ervin Chen
 * @date 2020/1/9 9:26
 */
@WebService(serviceName = "MaterialReplicateService",//对外发布的服务名
        //指定你想要的名称空间，通常使用使用包名反转
        targetNamespace = "http://service.meint.djhs.com",
        //服务接口全路径, 指定做SEI（Service EndPoint Interface）服务端点接口
        endpointInterface = "com.foreverwin.mes.integration.soap.material.service.MaterialReplicateService")
@Component
public class MaterialReplicateServiceImpl implements MaterialReplicateService {

    enum PurchaseType {
        P("F"),
        B("E");

        String value;

        PurchaseType(String value) {
            this.value = value;
        }

        public static PurchaseType fromValue(String value) {
            PurchaseType[] arr$ = values();
            int len$ = arr$.length;

            for (int i$ = 0; i$ < len$; ++i$) {
                PurchaseType c = arr$[i$];
                if (c.value.equals(value)) {
                    return c;
                }
            }

            throw new IllegalArgumentException(value);
        }
    }

    @Override
    @WebMethod
    public @WebResult(name = "replicateResponse")
    List<WebServiceResponse> replicateMaterial(@WebParam(name = "replicateRequest") List<MaterialReplicateRequest> replicateRequests) {
        if (replicateRequests.isEmpty()) {
            WebServiceResponse response = new WebServiceResponse();
            response.setStatus(ResponseStatus.S);
            response.setMessage("");
            return Lists.newArrayList(response);
        }

        return replicateRequests.stream().map(request -> {
            List<MaterialPlantData> materialPlantDatas = request.getMaterialPlantDatas();
            MaterialBasicData materialBasicData = request.getMaterialBasicData();

            for (MaterialPlantData materialPlantData : materialPlantDatas) {
                String site = materialPlantData.getSite();
                String item = materialBasicData.getItem();
                String revision = materialBasicData.getRevision();
                String description = materialBasicData.getDescription();
                String lotSize = materialBasicData.getLotSize();
                String unitOfMeasure = materialBasicData.getUnitOfMeasure();
                String itemGroup = materialBasicData.getItemGroup();
                String purchaseType = materialPlantData.getPurchaseType();
                String itemType = materialBasicData.getItemType();
                String isBatchManagement = materialBasicData.getIsBatchManagement();
                String qualityPeriod = materialPlantData.getQualityPeriod();

                if (StringUtils.isBlank(item)) {
                    return errorResponse("物料编号不允许为空");
                }
                if (StringUtils.isBlank(site)) {
                    return errorResponse("站点不允许为空");
                }
                if (StringUtils.isBlank(itemGroup)) {
                    return errorResponse("物料小类组ID不允许为空");
                }
                revision = StringUtils.isBlank(revision) ? "1" : revision;
                lotSize = StringUtils.isBlank(lotSize) ? "99999999" : lotSize;
                String itemBo = HandleEnum.ITEM.getHandle(site, item, revision);
                purchaseType = PurchaseType.fromValue(purchaseType).toString();

                try {
                    //创建修改物料
                    ItemConfigurationServiceInterface itemConfigurationServiceInterface = Services.getService("com.sap.me.productdefinition", "ItemConfigurationService", site);
                    ItemFullConfiguration itemFullConfiguration = itemConfigurationServiceInterface.readItem(new ObjectReference(itemBo));
                    if (itemFullConfiguration != null) {
                        itemFullConfiguration.setRevision(revision);
                        itemFullConfiguration.setCurrentRevision(Boolean.TRUE);
                        itemFullConfiguration.setUnitOfMeasurement(unitOfMeasure);
                        itemFullConfiguration.setItemType(ItemType.fromValue(purchaseType));
                        List<CustomValue> customValues = itemFullConfiguration.getCustomData();
                        //物料小类组ID自定义字段
                        CustomValue customValue = new CustomValue();
                        customValue.setName("BOTTOM_CLASSIFICATION");
                        customValue.setValue(itemGroup);
                        customValues.add(customValue);
                        //物料中类组ID自定义字段
                        customValue = new CustomValue();
                        customValue.setName("MEDIATE_CLASSIFICATION");
                        customValue.setValue(itemGroup.length() > 5 ? itemGroup.substring(0, 5) : itemGroup);
                        customValues.add(customValue);
                        //ERP批次管理
                        customValue = new CustomValue();
                        customValue.setName("BATCHMANAGEMENT");
                        customValue.setValue(isBatchManagement);
                        customValues.add(customValue);
                        //保质日期
                        customValue = new CustomValue();
                        customValue.setName("SHELF_LIFE");
                        customValue.setValue(qualityPeriod);
                        customValues.add(customValue);
                        itemFullConfiguration.setCustomData(customValues);
                        //描述
                        itemFullConfiguration.getItemTranslationList().clear();
                        ItemTranslation rl = new ItemTranslation();
                        rl.setLocale("zh");
                        rl.setDescription(description);
                        itemFullConfiguration.getItemTranslationList().add(rl);
                        itemConfigurationServiceInterface.updateItem(itemFullConfiguration);
                    } else {
                        ItemConfiguration itemConfiguration = new ItemConfiguration();
                        itemConfiguration.setItem(item);
                        itemConfiguration.setRevision(revision);
                        itemConfiguration.setCurrentRevision(Boolean.TRUE);
                        itemConfiguration.setUnitOfMeasurement(unitOfMeasure);
                        itemConfiguration.setItemType(ItemType.fromValue(purchaseType));
                        itemConfiguration.setLotSize(new BigDecimal(lotSize));
                        List<CustomValue> customValues = new ArrayList<>();
                        //物料小类组ID自定义字段
                        CustomValue customValue = new CustomValue();
                        customValue.setName("BOTTOM_CLASSIFICATION");
                        customValue.setValue(itemGroup);
                        customValues.add(customValue);
                        //物料中类组ID自定义字段
                        customValue = new CustomValue();
                        customValue.setName("MEDIATE_CLASSIFICATION");
                        customValue.setValue(itemGroup.length() > 5 ? itemGroup.substring(0, 5) : itemGroup);
                        customValues.add(customValue);
                        //ERP批次管理
                        customValue = new CustomValue();
                        customValue.setName("BATCHMANAGEMENT");
                        customValue.setValue(isBatchManagement);
                        customValues.add(customValue);
                        //保质日期
                        customValue = new CustomValue();
                        customValue.setName("SHELF_LIFE");
                        customValue.setValue(qualityPeriod);
                        customValues.add(customValue);
                        itemConfiguration.setCustomData(customValues);
                        //描述
                        ItemTranslation rl = new ItemTranslation();
                        rl.setLocale("zh");
                        rl.setDescription(description);
                        itemConfiguration.getItemTranslationList().add(rl);
                        itemConfigurationServiceInterface.createItem(itemConfiguration);
                    }
                } catch (BusinessException e) {
                    return errorResponse(Exceptions.convert(e).toString());
                }

                //检查物料组
                ItemGroupConfigurationServiceInterface itemGroupConfigurationServiceInterface = Services.getService("com.sap.me.productdefinition", "ItemGroupConfigurationService", site);
                String itemGroupBo = HandleEnum.ITEM_GROUP.getHandle(site, itemGroup);
                ItemGroupFullConfiguration itemGroupFullConfiguration = null;
                try {
                    itemGroupFullConfiguration = itemGroupConfigurationServiceInterface.readItemGroup(new ObjectReference(itemGroupBo));
                } catch (BusinessException e) {
                    e.printStackTrace();
                }
                try {
                    if (itemGroupFullConfiguration == null) {
                        ItemGroupConfiguration itemGroupConfiguration = new ItemGroupConfiguration();
                        itemGroupConfiguration.setItemGroup(itemGroup);
                        itemGroupConfiguration.setDescription(itemGroup);
                        List<ItemGroupMember> itemGroupMembers = new ArrayList<>();
                        ItemGroupMember itemGroupMember = new ItemGroupMember();
                        itemGroupMember.setItemRef(itemBo);
                        itemGroupMembers.add(itemGroupMember);
                        itemGroupConfiguration.setItemGroupMembers(itemGroupMembers);
                        itemGroupConfigurationServiceInterface.createItemGroup(itemGroupConfiguration);
                    } else {
                        List<ItemGroupMember> itemGroupMembers = new ArrayList<>();
                        ItemGroupMember itemGroupMember = new ItemGroupMember();
                        itemGroupMember.setItemRef(itemBo);
                        itemGroupMembers.add(itemGroupMember);
                        itemGroupFullConfiguration.setItemGroupMembers(itemGroupMembers);
                        itemGroupConfigurationServiceInterface.updateItemGroup(itemGroupFullConfiguration);
                    }
                } catch (BusinessException e) {
                    return errorResponse(Exceptions.convert(e).toString());
                }

            }

            WebServiceResponse response = new WebServiceResponse();
            response.setStatus(ResponseStatus.S);
            response.setMessage(request.getMaterialBasicData().getItem());
            return response;
        }).collect(Collectors.toList());
    }

    private WebServiceResponse errorResponse(String errorMessage) {
        WebServiceResponse response = new WebServiceResponse();
        response.setStatus(ResponseStatus.E);
        response.setMessage(errorMessage);
        return response;
    }

}
